package com.sfac.hqyj.springBoot.modules.test.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sfac.hqyj.springBoot.modules.common.entity.ResultEntity;
import com.sfac.hqyj.springBoot.modules.common.entity.SearchBean;
import com.sfac.hqyj.springBoot.modules.test.dao.CityDao;
import com.sfac.hqyj.springBoot.modules.test.entity.City;
import com.sfac.hqyj.springBoot.modules.test.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;

    @Override
    @Transactional
    public ResultEntity<City> insertCity(City city) {
        cityDao.insertCity(city);
        //int i=1/0;
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Insert success.", city);
    }

    @Override
    @Transactional
    public ResultEntity<City> updateCity(City city) {
        cityDao.updateCity(city);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Update success.", city);
    }

    @Override
    @Transactional
    public ResultEntity<Object> deleteCity(int cityId) {
        cityDao.deleteCity(cityId);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Delete success.");
    }

    @Override
    public City getCityByCityId(int cityId) {
        return cityDao.getCityByCityId(cityId);
    }

    @Override
    public List<City> getCitiesByCountryId(int countryId) {
        return Optional.ofNullable(cityDao.getCitiesByCountryId(countryId))
                .orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<City> getCitiesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(), searchBean.getPageSize());
        return new PageInfo<City>(
                Optional.ofNullable(cityDao.getCitiesBySearchBean(searchBean))
                        .orElse(Collections.emptyList()));
    }
}
